﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using System.Xml.Serialization; 


namespace ecdl.demo.persistence {
    public class GenericSerializer<dtoType> : DTODeserializer {
        private IEnumerable<IPersistenceContributor> contributors;

        [Inject]
        public GenericSerializer(IEnumerable<IPersistenceContributor> contributors) {
            this.contributors = contributors;
        }


        protected override void RegisterTypes() {

            foreach (var item in contributors) {
                item.ContributeTypesTypes(this);
            }
        }

        protected override void AddOverrides() {
            foreach (var item in contributors) {
                item.ContributeOverrides(this);
            }
        }

        protected override Type GetRootType() {
            return typeof(dtoType);
        }

        public dtoType Deseriliaze(System.IO.StreamReader stream) {
            string text = removeXSD(stream);

            XmlSerializer serializer = CreateSerializer();
            return (dtoType)serializer.Deserialize(new System.IO.StringReader(text));
        }

        private string removeXSD(System.IO.StreamReader stream) {
            string replaced = stream.ReadToEnd().Replace("xmlns=\"http://tempuri.org/ecdl.xsd\"", "");
            return replaced;
        }

        public void Serialize(System.IO.TextWriter stream, dtoType o) {
            CreateSerializer().Serialize(stream, o);
        }
    }
}
